package model

import (
	db "configuration/database"
	"database/sql"
	"fmt"
)

type Config struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

var tableName string = "szx_config"

func ConfigSet(key string, value string) (err error) {
	_, err = ConfigGet(key)
	if err != nil && err != sql.ErrNoRows {
		return
	}

	config := Config{Key: key, Value: value}
	if err == sql.ErrNoRows {
		err = config.Insert()
	} else {
		err = config.Update()
	}
	return
}

func ConfigGet(key string) (config Config, err error) {
	rs := db.DBConn.QueryRow(fmt.Sprintf("SELECT `key`, value FROM %s WHERE `key` = ?", tableName), key)
	err = rs.Scan(&config.Key, &config.Value)
	return
}

func ConfigAdd(key string, value string) (err error) {
	config := Config{Key: key, Value: value}
	err = config.Insert()
	return
}

func ConfigEdit(key string, value string) (err error) {
	config := Config{Key: key, Value: value}
	err = config.Update()
	return
}

func ConfigDel(key string) (err error) {
	config := Config{Key: key}
	err = config.Delete()
	return
}

func (c *Config) Insert() (err error) {
	_, err = db.DBConn.Exec(fmt.Sprintf("INSERT INTO %s (`key`, value) VALUES (?, ?)", tableName), c.Key, c.Value)
	return
}

func (c *Config) Update() (err error) {
	_, err = db.DBConn.Exec(fmt.Sprintf("UPDATE %s SET value = ? WHERE `key` = ?", tableName), c.Value, c.Key)
	return
}

func (c *Config) Delete() (err error) {
	_, err = db.DBConn.Exec(fmt.Sprintf("DELETE FROM %s WHERE `key` = ?", tableName), c.Key)
	return
}
